﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Simhopp.Common
{
    public class ScoreMap
    {
        /// <summary>
        /// Saves a score to the database
        /// </summary>
        /// <param name="score">The score to be saved</param>
        /// <returns>The index of the inserted/updated row</returns>
        public static int SaveScoreToDatabase(Score score)
        {
            if(score.Judge != null)
                score.JudgeId = UserMap.SaveUserToDatabase(score.Judge);
            return GenericMap.SaveObjectToDatabase(score);
        }

        public static void RemoveScoreFromDatabase(Score score)
        {
            GenericMap.RemoveObjectFromDatabase(score);
        }

        public static List<Score> GetAllScoresForOneDive(int diveId)
        {
            var diveList =
                MyDbConnection.ReadFromTable(String.Format(@"select * from Scores where DiveId='{0}'", diveId))
                    .Select(Score.GetFromDictionary)
                    .ToList();
            MyLogger.Debug(String.Format("Score for dive {0} loaded from database", diveId));
            return diveList;
        }

        public static List<Score> ReadAllScoresFromDatabase()
        {
            var dictionary = GenericMap.ReadAllObjectsFromDatabase(typeof(Score));
            try
            {
                var scores = dictionary.Select(Score.GetFromDictionary).ToList();
                MyLogger.Debug("All dictionaries converted to Score-objects");
                return scores;
            }
            catch (Exception e)
            {
                MyLogger.Error("Could not convert all dictionaries to Score-objects - " + e.Message);
                return null;
            }
        }

        public static Score ReadScoreFromDatabase(int id)
        {
            var dbResult = GenericMap.ReadObjectFromDatabase(id, typeof(Score));
            return dbResult == null ? null : Score.GetFromDictionary(dbResult);
        }
    }
}
